package com.seqb.common.task;

import cn.hutool.extra.mail.MailUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.seqb.common.config.RedisConfig;
import com.seqb.common.utils.RedisUtils;
import com.seqb.utils.DateUtils;
import org.apache.commons.lang.StringEscapeUtils;
import org.quartz.Job;
import org.quartz.JobExecutionContext;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.*;
import org.springframework.stereotype.Component;
import org.springframework.util.LinkedMultiValueMap;
import org.springframework.util.MultiValueMap;
import org.springframework.web.client.RestTemplate;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * @author lilinshen
 * @title 唯佳生活定时任务
 * @description 请填写相关描述
 * @date 2020/1/20
 */
@Component
public class WeiJiaShengHuoJob implements Job {
    private static final Logger LOGGER = LoggerFactory.getLogger(WeiJiaShengHuoJob.class);

    @Autowired
    private RedisUtils redisUtils;
    @Autowired
    private RestTemplate restTemplate;

    @Override
    public void execute(JobExecutionContext jobExecutionContext) {
        SignInWeijia();
    }

    /**
     * 唯佳生活每天签到活动
     */
    public boolean SignInWeijia() {
        try {
            //是否要记录日志
            String weijiaLog = System.getProperty("weijia.log");
            LOGGER.info("唯佳生活定时任务开始------lls-----" + DateUtils.format(new Date(), "yyyy-MM-dd HH:mm:ss"));
            SignInDaily();
            LOGGER.info("唯佳生活定时任务结束------lls-----" + DateUtils.format(new Date(), "yyyy-MM-dd HH:mm:ss"));
        } catch (Exception e) {
            e.printStackTrace();
        }
        return false;
    }

    /**
     * 唯佳生活每天签到领取积分
     */
    public void SignInDaily() {
        //刷新登录状态
        String requestUrl = "http://wj.wjtzcn.com/";
        HttpHeaders headers = new HttpHeaders();
        MultiValueMap<String, Object> requestMap = new LinkedMultiValueMap<>();
        List<String> cookieList = new ArrayList<>();
        cookieList.add("io=-utH1Xk_xnLFWLoOCKGl");
        cookieList.add("PHPSESSID=65445e816a38f999d294b7dd974ba6b9");
        headers.put("Cookie", cookieList);

        Object taskParams = redisUtils.get("taskParams");

        //记录是否失效
        boolean flag = true;
        Object flagRedis = redisUtils.get(RedisConfig.COM_PREFIX + this.getClass().getSimpleName());

        if (null != taskParams) {
            JSONArray parseArray = JSON.parseArray(taskParams.toString());
            for (int i = 0; i < parseArray.size(); i++) {
                JSONObject item = parseArray.getJSONObject(i);
                String type = item.getString("type");
                if (type.indexOf("WeiJiaShengHuoJob") >= 0) {
                    JSONArray value = item.getJSONArray("value");
                    cookieList = new ArrayList<>();
                    for (int j = 0; j < value.size(); j++) {
                        JSONObject jsonObject = value.getJSONObject(j);
                        cookieList.add(jsonObject.getString("key") + "=" + jsonObject.getString("value"));
                        headers.put("Cookie", cookieList);
                    }

                    HttpMethod httpMethod = HttpMethod.GET;
                    HttpEntity httpEntity = new HttpEntity(requestMap, headers);
                    ResponseEntity<String> responseEntity = restTemplate.exchange(requestUrl, httpMethod, httpEntity, String.class);
                    HttpStatus status = responseEntity.getStatusCode();
                    if (status.equals(HttpStatus.OK)) {
                        String entityBody = responseEntity.getBody();
                    }
                    //每天签到请求
                    requestUrl = "http://wj.wjtzcn.com/signin/signinsubmit?type=1";
                    responseEntity = restTemplate.exchange(requestUrl, httpMethod, httpEntity, String.class);
                    status = responseEntity.getStatusCode();
                    if (status.equals(HttpStatus.OK)) {
                        String entityBody = responseEntity.getBody();
                        entityBody = StringEscapeUtils.unescapeJava(entityBody);

                        //判断唯佳签到生活cookie失效
                        try {
                            JSON.parse(entityBody);
                        } catch (Exception e) {
                            flag = false;
                        }
                        LOGGER.info("签到领取积分：" + entityBody);
                    }
                }
            }
        }

        if (!flag) {
            LOGGER.info("唯佳生活定时任务，执行失败。");
        }

        if (flag && null == flagRedis) {
            //设置一天失效时间的key，每天只发一次邮件通知
            redisUtils.set(RedisConfig.COM_PREFIX + this.getClass().getSimpleName(), true, 86400);
            //发送邮件通知唯佳生活签到失效
            MailUtil.send("lilinshen@cecjx.com", "唯佳生活定时任务", "唯佳生活定时任务，用户cookie失效，请及时更新用户cookie信息。", false);
        }

    }
}
